package com.raising.framework.filter;

import com.raising.framework.config.JConfig;
import com.raising.utils.EncodesUtils;
import com.raising.utils.JStringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 会话退出监听
 * 会话监听
 */
public class ForceLogoutFilter extends AccessControlFilter {
    /**
     * 此方法判断当前请求是否session失效
     * @author GaoYuan
     * @datetime 2017/12/15 上午9:29
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Session session = getSubject(request, response).getSession(false);
        if(session == null) {
            return true;
        }
        return session.getAttribute(JConfig.SESSION_FORCE_LOGOUT_KEY) == null;
    }
    /**
     * session失效再跳转后，会进入此方法
     * @author GaoYuan
     * @datetime 2017/12/15 上午9:28
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        try {
            //强制退出
            getSubject(request, response).logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpServletRequest re = (HttpServletRequest)request;
        String oldUrl = EncodesUtils.urlEncode(re.getRequestURL() + "?" + re.getQueryString());

        String loginUrl = getLoginUrl() + (getLoginUrl().contains("?") ? "&" : "?") + "forceLogout=1";
        if(JStringUtils.isNotBlank(oldUrl)){
            loginUrl = loginUrl + "&jumpUrl="+oldUrl;
        }
        WebUtils.issueRedirect(request, response, loginUrl);
        return false;
    }
}
